package com.wandian.audio.mvvm.audiomain;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.GlideUtil;
import com.mylib.libcore.utils.MyAnimatorUpdateListener;
import com.mylib.libcore.utils.MyStringUtils;
import com.mylib.libcore.utils.StatusBarUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.audio.R;
import com.wandian.audio.bean.MusicBean;
import com.wandian.audio.config.AudioConfig;
import com.wandian.audio.databinding.AudioActivityMainBinding;
import com.wandian.audio.dialog.AudioHistoryListDialogWindow;
import com.wandian.audio.service.AudioInService;
import com.wandian.audio.service.AudioService;
import com.wandian.audio.tools.MusicCollector;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import me.jessyan.autosize.utils.ScreenUtils;

import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_LIST;
import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_MODEL_KEY;
import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_RANDOM;
import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_SINGLE;
import static com.wandian.audio.config.AudioConfig.AUDIO_SELECT_MUSIC_INDEX;


/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 音频播放主页面
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_AUDIO_MAIN)
public class AudioMainActivity extends  BaseMVVMActivity<AudioMainActivityViewModel> implements AudioHistoryListDialogWindow.AudioDialogItemClink{
    private AudioActivityMainBinding dataBinding;
    private  WifiManager.WifiLock wifiLock;
    private AudioConnection audioConnection;
    private AudioInService audioInService;
    private int duration = 100;
    private int progress = 0;
    private int index = 0;
    private int playModel = 1;//默认播放模式顺序播放
    private  LinearInterpolator lin;    //旋转动画
    private  ObjectAnimator anim;
    private  MyAnimatorUpdateListener listener;
    private String musicType;
    private int musicIndex = 0;
    private MusicBean musicBean;
    private AudioHistoryListDialogWindow audioHistoryListDialogWindow; //弹框
    private Handler handler = new Handler();
    private Runnable mRunnable = new Runnable() {
        public void run() {
            index++;
            Log.d("handler",index+"");
            startUpdataProgress();
            handler.postDelayed(mRunnable, 1000);
        }
    };

    @Override
    public void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.audio_activity_main);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        //获取音乐数据
        initMusicSelectIndex();
        //初始化页面
        initViewData();
        initAnimation();
        initClink();
        initMediaPlayer();
        handler.post(mRunnable);
    }

    //初始化选中音乐下标
    private void initMusicSelectIndex(){
        String key = getIntent().getStringExtra("key");
        if(!UIUtils.isEmpty(key)){
            if(key.equals(AudioConfig.INTOMAIN)){
                String selectIndex = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(AUDIO_SELECT_MUSIC_INDEX);
                if(!UIUtils.isEmpty(selectIndex)){
                    int index =  Integer.parseInt(selectIndex);
                    if(index<MusicCollector.getSongsList().size())musicIndex = index;
                }
            }
        }else {
            Bundle bundle = getIntent().getExtras();
            if(!UIUtils.isEmpty(bundle)){
                musicType = bundle.getString("music_type");
                String musicId = bundle.getString("music_id")+"";
                Log.d("musicIndex","musicIndex===>"+musicId);
                if(musicType.equals("network")){
                    musicIndex = MusicCollector.getSongIndexByID(musicId);
                    Log.d("musicIndex","musicIndex=network=>"+musicId);
                }else {
                    Log.d("musicIndex","musicIndex=local=>"+musicId);
                    musicIndex = MusicCollector.getSongIndexByLocal(musicId);
                }
            }
        }
        if(!UIUtils.isEmpty(MusicCollector.getSongsList()) && MusicCollector.getSongsList().size()>musicIndex){
            musicBean = MusicCollector.getSongsList().get(musicIndex);
        }else {
            musicBean = MusicCollector.getSongsList().get(0);
        }
        Log.d("musicIndex","musicIndex=="+musicIndex);
    }

    private void initViewData(){

        //系统状态栏高度
        int statusBarHeight = ScreenUtils.getStatusBarHeight();
        LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) dataBinding.viewSystem.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
        linearParams.height = statusBarHeight;
        dataBinding.viewSystem.setLayoutParams(linearParams);
        dataBinding.bindTool.toolBarTvTitle.setText(musicBean.getName()+"");
        GlideUtil.loadFilletPic(this,musicBean.getThumb(), dataBinding.ivSoundBg,50);
        //   GlideUtil.loadFilletPic(this,musicPic, dataBinding.ivNiceImageView,180);
        // GlideUtil.setDrawableToGauss(AudioMainActivity.this,getResources().getDrawable(R.drawable.launch_image), dataBinding.ivSoundBg,50);

        //设置播放模式
        String musicModel =  AppContext.getInstance().getAppPreferencesHelper().getKeyValue(AUDIO_PLAY_MODEL_KEY);
        if(UIUtils.isEmpty(musicModel)){
            notifyPlayModelUI(AUDIO_PLAY_LIST);
        }else {
            notifyPlayModelUI(musicModel);
        }

    }

    private void initClink(){
        dataBinding.bindTool.toolBarIvBack.setOnClickListener(v -> finish());
        dataBinding.bindTool.toolBarTitleRightIv.setOnClickListener(v -> ToastUtil.show("稍等"));

        dataBinding.ivPlayerControl.setOnClickListener(v -> {
            audioInService.upDataAudioPlayState();
            //切换播放状态UI
            upDataAudioPlayUI();
        });
        //播放列表
        dataBinding.ivPlayList.setOnClickListener(v -> {
            showCatalogDialog();
        });
        //播放模式
        dataBinding.ivPlayMode.setOnClickListener(v -> {
            playModel++;
            if(playModel>3) playModel = 1;
            notifyPlayModelUI(playModel+"");
            AppContext.getInstance().getAppPreferencesHelper().setKeyValue(AUDIO_PLAY_MODEL_KEY,playModel+"");
        });
        //上一级
        dataBinding.ivUpLevel.setOnClickListener(v -> audioInService.playUpLevel());
        //下一级
        dataBinding.ivNextLevel.setOnClickListener(v ->audioInService.playNextLevel());
        //目录
        dataBinding.llAudioMl.setOnClickListener(v -> { showCatalogDialog(); });
        //进度条
        dataBinding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                audioInService.seekTo(seekBar.getProgress());
            }
        });
    }

    private void notifyPlayModelUI(String playModel){
        switch (playModel){
            case AUDIO_PLAY_LIST:
                dataBinding.ivPlayMode.setImageResource(R.drawable.img_sound_list);
                break;
            case AUDIO_PLAY_RANDOM:
                dataBinding.ivPlayMode.setImageResource(R.drawable.img_sound_random);
                break;
            case AUDIO_PLAY_SINGLE:
                dataBinding.ivPlayMode.setImageResource(R.drawable.img_sound_single);
                break;
        }
    }

    //展示目录弹框
    private void showCatalogDialog(){
        try {
            audioHistoryListDialogWindow = new AudioHistoryListDialogWindow(getContext(),this::itemClink);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            if(!UIUtils.isEmpty(dataBinding.rlAudioMain)){
                audioHistoryListDialogWindow.showAtLocation(dataBinding.rlAudioMain, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新播放UI
     */
    private void upDataAudioPlayUI(){
        if(!UIUtils.isEmpty(audioInService)){
            //切换播放状态UI
            boolean isPlay = audioInService.isPlay();
            if(isPlay){//正在播放
                dataBinding.ivPlayerControl.setImageResource(R.drawable.img_sound_start);
            }else {
                dataBinding.ivPlayerControl.setImageResource(R.drawable.img_sound_stop);
            }
            startUpdataProgress();
        }
    }


    /**
     * 开始更新进度
     */
    private void startUpdataProgress(){
        //获取当前进度
        if(!UIUtils.isEmpty(audioInService)){
            //更新进度时间
            duration =  audioInService.getDuration();
            progress = audioInService.getProgress();
            //进度最大值
            dataBinding.seekBar.setMax(duration);
            //更新进度条
            dataBinding.seekBar.setProgress(progress);
            //更新时间进度
            upTimeProgress();
        }
    }

    /**
     * 开始更新时间进度
     */
    private void upTimeProgress(){
        //此时已在主线程中，可以更新UI了
        //更新进度时间
        dataBinding.tvLeftTime.setText(MyStringUtils.progressToTimeString(progress));
        dataBinding.tvRightTime.setText(MyStringUtils.progressToTimeString(duration));
    }

    private void initAnimation(){
        lin = new LinearInterpolator();//声明为线性变化
        anim = ObjectAnimator.ofFloat(dataBinding.ivNiceImageView, "rotation", 0f, 360f);//设置动画为旋转动画，角度是0-360
        anim.setDuration(15000);//时间15秒，这个可以自己酌情修改
        anim.setInterpolator(lin);
        anim.setRepeatMode(ValueAnimator.RESTART);//设置重复模式为重新开始
        anim.setRepeatCount(-1);//重复次数为-1，就是无限循环
        listener = new MyAnimatorUpdateListener(anim);//将定义好的ObjectAnimator传给MyAnimatorUpdateListener监听
        anim.addUpdateListener(listener);//给动画加监听
    }


    private void initMediaPlayer(){
        //通过audioService开启服务播放音乐
        Intent intentService = new Intent(this, AudioService.class);
        //通过intent 将数据传递出去
        intentService.putExtra("music_index",musicIndex+"");
        //开启服务
        startService(intentService);
        //绑定服务
        if(UIUtils.isEmpty(audioConnection)){
            audioConnection = new AudioConnection();
        }
        bindService(intentService,audioConnection,BIND_AUTO_CREATE);
        // 初始化wifi锁
        if(UIUtils.isEmpty(wifiLock)){
            wifiLock = ((WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
        }
    }


    @Override
    public void itemClink(int playIndex) {
        playItemMusic(playIndex);
    }

    //播放指定某一首
    private  void playItemMusic(int playIndex){
        Log.d("musicIndex","playIndex=="+playIndex);
        String indexLocal = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(AUDIO_SELECT_MUSIC_INDEX)+"";
        if(!indexLocal.equals(playIndex+"")){
            audioInService.playItemMusic(playIndex);
        }else {
            if(!audioInService.isPlay()){
                audioInService.upDataAudioPlayState();
            }
        }
    }


    class AudioConnection implements ServiceConnection {

        /**
         * service以外连接的时候
         * @param name
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            audioInService = (AudioInService)service;
        }

        /**
         * service连接的时候
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBusMessage(ChangeMessage changeMessage) {
        try {
            if(!UIUtils.isEmpty(changeMessage) && !UIUtils.isEmpty(changeMessage.getIsChange())){
                if(changeMessage.getIsChange().equals("notifyUpDataAudioUi")){
                    if(!UIUtils.isEmpty(changeMessage.getValue())){
                        musicIndex = Integer.parseInt(changeMessage.getValue());
                        if(UIUtils.isEmpty(MusicCollector.getSongsList()) || MusicCollector.getSongsList().size()<=musicIndex){
                            ToastUtil.show("歌曲数据错误！");
                            return;
                        }
                        musicBean =  MusicCollector.getSongsList().get(musicIndex);
                        if(!UIUtils.isEmpty(musicBean)){
                            upDataAudioPlayUI();
                            dataBinding.bindTool.toolBarTvTitle.setText(musicBean.getName()+"");
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        //将线程销毁掉
        handler.removeCallbacks(mRunnable);
        //接触订阅
        EventBus.getDefault().unregister(this);
        //解绑服务
        unbindService(audioConnection);
        super.onDestroy();
    }
}
